package com.bigknow.appstore.web.base.service.impl;

import com.bigknow.appstore.web.base.dao.IRoleDao;
import com.bigknow.appstore.web.base.dao.IUserDao;
import com.bigknow.appstore.web.base.service.IDelegatingService;
import com.bigknow.appstore.web.framework.util.GlobalConstant;
import com.bigknow.appstore.web.base.dao.IPermissionDao;
import com.bigknow.appstore.web.base.entity.Permission;
import com.bigknow.appstore.web.base.entity.Role;
import com.bigknow.appstore.web.base.entity.User;
import com.bigknow.appstore.web.framework.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 供shiro认证授权时使用
 * Created by Administrator on 2015/3/20.
 */
@Service("delegatingService")
public class DelegatingService extends BaseService implements IDelegatingService {

    @Autowired
    private IPermissionDao permissionDao;
    @Autowired
    private IRoleDao roleDao;
    @Autowired
    private IUserDao userDao;

    @Override
    public User findLoginUser(String account) {
        User user = new User();
        user.setAccount(account);
        User loginUser = this.userDao.findFirst(user);
        if (loginUser != null) {
            return loginUser;
        } else {
            throw new RuntimeException(springUtils.getMessage(GlobalConstant.USER_NOT_EXIST));
        }
    }

    @Override
    public List<Permission> getPermissionsByUserId(String id) {
        List<Permission> permissionList = new ArrayList<>();
        User user = this.userDao.get(id);
        if (user != null) {
            user.getRoleIds();
            List<Role> roleList = this.roleDao.findById(user.getRoleIds());
            roleList.forEach(role -> {
                permissionList.addAll(this.permissionDao.findById(role.getPermissionIds()));
            });
        }

        return permissionList;
    }

    @Override
    public Set<String> getPermissionsAsSet(String userId) {
        List<Permission> permissions = this.getPermissionsByUserId(userId);
        Set<String> set = new HashSet<String>();
        for (Permission permission : permissions) {
            if (StringUtils.isEmpty(permission.getPageUrl())) continue;//为空字符串的url不能加入
            set.add(permission.getPageUrl());
        }
        return set;
    }

    @Override
    public Set<String> getRolesAsSet(String userId) {
        User user = this.userDao.get(userId);
        if (user != null) {
            List<Role> roles = this.roleDao.findById(user.getRoleIds());
            return roles.stream().map(Role::getName).collect(Collectors.toSet());
        }

        return new HashSet<>();
    }

}
